import matplotlib.pyplot as plt
import numpy as np
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score

#数据处理
x=np.array([[19,30],[30,40],[39,47],[40,52],[47,50],[50,55],[60,60],[62,65],[73,70],[75,82],[77,85],[90,95],[92,90]])
y=np.array([0,0,0,0,0,0,1,1,1,1,1,1,1])
x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=0)

#定义可选取的K值范围
k_range=range(2,11)#k值的取值范围
k_errors=[]#每个k值所对应的误差率

#计算每个k值所对应的误差率
for k in k_range:
    model = KNeighborsClassifier(k)
    scores = cross_val_score(model,x,y,cv=5,scoring='accuracy')
    k_errors.append(1-scores  .mean())

#输出到面板
plt.rcParams['font.sans-serif']=['SimHei']
plt.plot(k_range,k_errors,'r-')
plt.xlabel('k值')
plt.ylabel('误差率')
plt.show()

#待测样板
pred_x=[[85,65]]

model1 = KNeighborsClassifier(5)
model1.fit(x_train,y_train)
pred1=model1.predict(pred_x)
print(f'当k=5时,预测样本的分类结果为：{pred1}')

model2 = KNeighborsClassifier(7)
model2.fit(x_train,y_train)
pred2=model2.predict(pred_x)
print(f'当k=7时,预测样本的分类结果为：{pred2}')